﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using FinancePortal.Business.Implementation;
using FinancePortal.Business.Infraestructure;
using FinancePortal.Business.Repository;
using Microsoft.Practices.Unity;
using System.Web.Security;

namespace FinancePortal.Web.IoC
{
    public class UnityDependencyResolver : IDependencyResolver, IDisposable
    {
        public UnityDependencyResolver()
        {
            //var factory = new UnityControllerFactory(Container);
            //ControllerBuilder.Current.SetControllerFactory(factory);
        }

        private static IUnityContainer Container
        {
            get
            {
                var container = HttpContext.Current.Items["Container"] as IUnityContainer;

                if (container == null)
                {
                    //var session = new NHibernateHelper().SessionFactory.OpenSession();
                    //.RegisterInstance<ISession>(session, new HttpContextLifetimeManager<ISession>())

                    container = new UnityContainer()
                    .RegisterType<NHibernateHelper>()
                    .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())
                    .RegisterType<IActivityRepository, ActivityRepository>(new HttpContextLifetimeManager<IActivityRepository>())
                    .RegisterType<IActivityScheduleRepository, ActivityScheduleRepository>(new HttpContextLifetimeManager<IActivityScheduleRepository>())
                    .RegisterType<IAreaRepository, AreaRepository>(new HttpContextLifetimeManager<IAreaRepository>())
                    .RegisterType<IResourceRepository, ResourceRepository>(new HttpContextLifetimeManager<IResourceRepository>())
                    .RegisterType<IVacationScheduleRepository, VacationScheduleRepository>(new HttpContextLifetimeManager<IVacationScheduleRepository>())
                    ;

                    container.BuildUp(typeof(AccountMembershipProvider), Membership.Provider);
                    container.BuildUp(typeof(AccountRoleProvider), Roles.Provider);//Membership.);

                    HttpContext.Current.Items["Container"] = container;
                }
                return container;
            }
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return Container.Resolve(serviceType);
            }
            catch
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return Container.ResolveAll(serviceType);
            }
            catch
            {
                return new List<object>();
            }
        }

        public void Dispose()
        {
            Container.Dispose();
        }
    }
}